﻿using Batman.Core;
using Batman.Core.Utilities;
using Batman.IdentityServer.Weixin;
using Batman.Web.Api.Todo.Dtos;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Threading.Tasks;

namespace Batman.Web.Api.Todo.Controllers.MiniProgram
{
    [ApiController]
    [Route("api/[controller]")]
    public class MiniProgramController : ControllerBase
    {
        private static readonly string host = "https://api.weixin.qq.com/sns/jscode2session";

        private IConfiguration configuration;
        public MiniProgramController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        [Route("token")]
        public async Task<ResponseBase<WeixinOpenTokenResponse>> Token(string code)
        {
            if (string.IsNullOrWhiteSpace(code))
                return new ResponseBase<WeixinOpenTokenResponse>(false, "code 是空的");

            string appId = configuration["MiniProgram:AppId"];
            string secret = configuration["MiniProgram:Secret"];

            var requestApi = $"{host}?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";

            using (var client2 = new HttpClient())
            {
                var res = await client2.GetAsync(requestApi);
                var content = await res.Content.ReadAsStringAsync();

                var userInfo = JsonUtil.Parse<MiniProgramLoginInfoResponse>(content);

                var cache = new DiscoveryCache(configuration["Auth:Authority"]);
                var disco = await cache.GetAsync();

                var client = new HttpClient();

                var tokenResponse = await client.RequestWeixinOpenTokenAsync(new WeixinOpenTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    OpenId = userInfo.openid,

                    ClientId = configuration["Auth:ClientId"],
                    ClientSecret = configuration["Auth:ClientSecret"],
                    Scope = "todo",

                });
                if (!tokenResponse.Success)
                {
                    return tokenResponse;
                }

                return tokenResponse;
            }
        }
    }
}
